package kr.co.creativeideas.gooq.common;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import kr.co.creativeideas.gooq.entity.DataReceive;

import org.xmlpull.v1.XmlPullParser;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.util.Xml;

public class XmlParser {

	static final String ROOT = "root";
	static final String RANK = "rank";
	static final String ID = "id";
	static final String SCORE = "score";
	static final String ITEM = "item";

	private URL xmlUrl;
	private ProgressDialog mDialog;

	public XmlParser(Context _context, String _xmlUrl) {
		try {
			xmlUrl = new URL(_xmlUrl);
			mDialog = new ProgressDialog(_context);
			mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mDialog.setMessage("Loading...");
			mDialog.setCancelable(false);
		} catch (MalformedURLException e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public InputStream getInputStream() {
		try {
			return xmlUrl.openConnection().getInputStream();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public List<DataReceive> Parser() {
		List<DataReceive> record = null;
		XmlPullParser parser = Xml.newPullParser();
		try {
			parser.setInput(this.getInputStream(), null);
			int eventType = parser.getEventType();
			DataReceive currentRecord = null;
			record = new ArrayList<DataReceive>();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				String name = null;
				switch (eventType) {				
				case XmlPullParser.START_TAG:
					name = parser.getName();
					if (name.equals(ITEM)) {
						currentRecord = new DataReceive();
					} else if (currentRecord != null) {
						if (name.equals(RANK)) {
							currentRecord.setRank(parser.nextText());
						} else if (name.equals(ID)) {
							currentRecord.setId(parser.nextText());
						} else if (name.equals(SCORE)) {
							currentRecord.setScore(parser.nextText());
						}
					}
					break;
				case XmlPullParser.END_TAG:
					name = parser.getName();
					if (name.equals(ITEM)) {
						record.add(currentRecord);
					}
					break;
				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("::XMLParser::", e.getMessage(), e);
			throw new RuntimeException(e);
		}
		mDialog.dismiss();
		return record;
	}
}
